<template>
  <a-button type="primary" style="padding: 4px 6px" @click="onClick">
    新建项目
  </a-button>
  <project-modal
    v-model:open="open"
    v-model:title="addTitle"
    :context-data="propsModalData"
    @add="handleAdd"
  />
</template>
<script setup>
import { newProject } from '@/api/catalog-personal.js'
import ProjectModal from './new-project-modal.vue'
import { message } from 'ant-design-vue'
import { useDataSourceManager } from './provide-context.js'
import { ref, nextTick } from 'vue'

/**
 * 全局数据
 */
let { update } = useDataSourceManager()
let propsModalData = ref({})
let loading = ref(false)
let open = ref(false)
let addTitle = ref('新建项目')

/**
 * 新增操作
 */
function onClick() {
  open.value = true
  propsModalData.value = {
    btnType: 'add',
    data: null,
  }
}
let emit = defineEmits(['newProject'])
async function handleAdd(data) {
  loading.value = true
  try {
    let params = {
      prjName: data.title,
    }
    await newProject(params)
    await update()
    loading.value = false
    open.value = false
    message.success('新建成功。')
    await nextTick()
    emit('newProject')
  } catch (e) {
    loading.value = false
    open.value = false
  }
}
</script>
